package com.example.skudemo.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.skudemo.core.exception.CommonException;
import com.example.skudemo.dto.AttributeDTO;
import com.example.skudemo.dto.AttributeQueryParam;
import com.example.skudemo.dto.AttributeValueDTO;
import com.example.skudemo.enums.StatusEnum;
import com.example.skudemo.model.BaseEntity;
import com.example.skudemo.model.AttributeEntity;
import com.example.skudemo.model.AttributeValueEntity;
import com.example.skudemo.service.IAttributeService;
import com.example.skudemo.service.IAttributeValueService;
import com.example.skudemo.utils.ApiResult;
import com.example.skudemo.vo.PageResponseVO;
import com.example.skudemo.vo.AttributeListVO;
import com.example.skudemo.vo.AttributeVO;
import com.example.skudemo.vo.AttributeValueVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品属性表 前端控制器
 * </p>
 *
 * @author 水痕
 * @since 2023-11-17
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/attribute")
public class AttributeController {
    @Autowired
    private IAttributeService propertyService;

    @Autowired
    private IAttributeValueService propertyValueService;

    /**
     * 创建
     *
     * @param req PropertyDTO
     * @return ApiResult
     */
    @PostMapping
    @Transactional
    public ApiResult createPropertyApi(@RequestBody @Valid AttributeDTO req) {
        // 1.判断是否已经存在
        LambdaQueryWrapper<AttributeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttributeEntity::getName, req.getName());
        if (!ObjectUtil.isNull(this.propertyService.getOne(queryWrapper))) {
            throw new CommonException(String.format("%s已经存在,不能重复创建", req.getName()));
        }
        AttributeEntity attributeEntity = new AttributeEntity();
        BeanUtil.copyProperties(req, attributeEntity);
        if (!this.propertyService.save(attributeEntity)) {
            AttributeController.log.error("插入属性失败");
            throw new CommonException("创建失败");
        }
        List<AttributeValueEntity> attributeValueEntityList = new ArrayList<>();
        for (AttributeValueDTO item : req.getPropertyValueList()) {
            AttributeValueEntity attributeValueEntity = new AttributeValueEntity();
            BeanUtil.copyProperties(item, attributeValueEntity);
            attributeValueEntity.setAttributeId(attributeEntity.getId());
            attributeValueEntityList.add(attributeValueEntity);
        }
        if (!this.propertyValueService.saveBatch(attributeValueEntityList)) {
            log.error("插入属性值失败");
            throw new CommonException("创建失败");
        }
        return ApiResult.success("创建成功");
    }

    @GetMapping("list")
    public ApiResult getPropertyList() {
        LambdaQueryWrapper<AttributeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttributeEntity::getStatus, StatusEnum.NORMAL.getCode());
        List<AttributeEntity> attributeEntityList = this.propertyService.list(queryWrapper);
        List<AttributeListVO> attributeListVOS = BeanUtil.copyToList(attributeEntityList, AttributeListVO.class);
        return ApiResult.success(attributeListVOS);
    }

    /**
     * 根据id获取数据
     *
     * @param id Integer
     * @return ApiResult
     */
    @GetMapping("{id}")
    public ApiResult getPropertyByIdApi(@PathVariable @Valid Integer id) {
        // 1.获取当前的属性
        LambdaQueryWrapper<AttributeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttributeEntity::getId, id);
        AttributeEntity attributeEntity = this.propertyService.getOne(queryWrapper);
        if (ObjectUtil.isNull(attributeEntity)) {
            return ApiResult.error("传递的id错误");
        }
        AttributeVO attributeVO = new AttributeVO();
        BeanUtil.copyProperties(attributeEntity, attributeVO);
        // 2.查询属性
        LambdaQueryWrapper<AttributeValueEntity> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AttributeValueEntity::getAttributeId, id);
        List<AttributeValueEntity> propertyValueEntities = this.propertyValueService.list(queryWrapper1);
        List<AttributeValueVO> attributeValueVOS = BeanUtil.copyToList(propertyValueEntities, AttributeValueVO.class);
        attributeVO.setPropertyValueList(attributeValueVOS);
        return ApiResult.success(attributeVO);
    }

    /**
     * 分页获取数据
     *
     * @param queryParam 请求参数
     * @return ApiResult
     */
    @GetMapping
    public ApiResult getPropertyPageApi(AttributeQueryParam queryParam) {
        QueryWrapper<AttributeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.
                like(queryParam.getName() != null, "name", queryParam.getName()).
                eq(queryParam.getStatus() != null, "status", queryParam.getStatus()).
                lambda().
                orderByDesc(AttributeEntity::getId);
        // 分页器
        Page<AttributeEntity> pager = new Page<>(queryParam.getPageNumber(), queryParam.getPageSize());
        IPage<AttributeEntity> propertyEntities = this.propertyService.page(pager, queryWrapper);
        // 获取全部的id
        List<Integer> idList = propertyEntities.getRecords().stream().map(BaseEntity::getId).collect(Collectors.toList());
        LambdaQueryWrapper<AttributeValueEntity> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(AttributeValueEntity::getAttributeId, idList);
        List<AttributeValueEntity> propertyValueEntities = this.propertyValueService.list(queryWrapper1);
        // 1.将propertyValueEntities转成map[id][]PropertyEntity 形式
        Map<Integer, List<AttributeValueEntity>> map = new HashMap<>();
        for (AttributeValueEntity item : propertyValueEntities) {
            List<AttributeValueEntity> currentItem = map.get(item.getAttributeId());
            if (ObjectUtil.isNull(currentItem)) {
                currentItem = new ArrayList<>();
            }
            currentItem.add(item);
            map.put(item.getAttributeId(), currentItem);
        }
        List<AttributeVO> list = new ArrayList<>();
        for (AttributeEntity item : propertyEntities.getRecords()) {
            AttributeVO attributeVO = BeanUtil.copyProperties(item, AttributeVO.class);
            List<AttributeValueEntity> attributeValueEntityList = map.get(item.getId());
            List<AttributeValueVO> attributeValueVOS = BeanUtil.copyToList(attributeValueEntityList, AttributeValueVO.class);
            attributeVO.setPropertyValueList(attributeValueVOS);
            list.add(attributeVO);
        }
        PageResponseVO<AttributeVO> result = new PageResponseVO<>();
        result.setList(list);
        result.setTotal(propertyEntities.getTotal());
        result.setPageNumber(propertyEntities.getSize());
        result.setPageSize(propertyEntities.getCurrent());
        return ApiResult.success(result);
    }
}
